﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace GBricks.Collections
{
  partial class Comparers
  {
    public static Comparer<Type> ByType {
      [DebuggerStepThrough]
      get {
        Contract.Ensures(Contract.Result<Comparer<Type>>() != null);
        return TypeComparer.Instance;
      }
    }

    [Serializable]
    private sealed class TypeComparer : Comparer<Type>, IEquatable<TypeComparer>
    {
      internal static readonly TypeComparer Instance = new TypeComparer();

      public override int Compare(Type x, Type y) {
        if(x == null) {
          return y == null ? 0 : -1;
        } else if(y == null) {
          return 1;
        } else if(x == y) {
          return 0;
        } else if(x.IsAssignableFrom(y)) {
          return 1;
        }//if

        return -1;
      }

      public override bool Equals(object obj) {
        return Equals(obj as TypeComparer);
      }

      public override int GetHashCode() {
        return 19;
      }

      #region IEquatable<TypeComparer> Members

      public bool Equals(TypeComparer other) {
        return other != null;
      }

      #endregion IEquatable<TypeComparer> Members
    }
  }
}
